package team.southcat.wsyygh.hospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.southcat.wsyygh.common.result.Result;
import team.southcat.wsyygh.hospital.service.ScheduleService;
import team.southcat.wsyygh.model.pojo.hospital.Department;
import team.southcat.wsyygh.model.pojo.hospital.Doctor;
import team.southcat.wsyygh.model.pojo.hospital.DoctorVo;
import team.southcat.wsyygh.model.pojo.hospital.Schedule;
import team.southcat.wsyygh.hospital.mapper.DoctorMapper;
import team.southcat.wsyygh.hospital.service.DepartmentService;
import team.southcat.wsyygh.hospital.service.DoctorService;
import team.southcat.wsyygh.model.pojo.user.Admin;
import team.southcat.wsyygh.user.client.AdminFeignClient;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author QiuSiYi
 * @since 2023-04-20
 */
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {

    @Resource
    private DepartmentService departmentService;

    @Resource
    private ScheduleService scheduleService;

    @Resource
    private DoctorService doctorService;

    @Autowired
    private AdminFeignClient adminFeignClient;

    @Override
    public Page getDoctorPageList(int page, int pageSize, Doctor doctor, String adminId) {
        //分页构造器,传入页码和大小
        Page<Doctor> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();

        //只查询当前可以管理的医院
        Object adminObj = adminFeignClient.getAdminById(Integer.valueOf(adminId)).getData();
        Admin admin = JSONObject.parseObject(JSON.toJSONString(adminObj), Admin.class);
        queryWrapper.eq(Doctor::getHospitalId, admin.getHospitalId());

        //添加查询条件
        //科室名称
        queryWrapper.eq(doctor.getDepartmentId()!=null,Doctor::getDepartmentId,doctor.getDepartmentId());
        //医生名称
        queryWrapper.like(doctor.getDoctorName() != null, Doctor::getDoctorName, doctor.getDoctorName());

        //执行查询
        this.page(pageInfo, queryWrapper);

        //对象拷贝为Vo对象Page
        Page<DoctorVo> voPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, voPage);

        //取出数据并赋值转换
        List<Doctor> records = pageInfo.getRecords();

        //使用流转换,遍历将医生id改为医生名字
        List<DoctorVo> DoctorVos= records.stream().map((doctor1) -> {
            DoctorVo doctorVo1 = new DoctorVo();
            BeanUtils.copyProperties(doctor1, doctorVo1);

            if(doctor1.getGender()==0){
                doctorVo1.setGenderName("女");
            }else if(doctor1.getGender()==1){
                doctorVo1.setGenderName("男");
            }

            //根据科室id查询科室数据
            Department department = departmentService.getById(doctor1.getDepartmentId());
            doctorVo1.setDepartmentName(department.getDepartmentName());

            Department department1 = departmentService.getById(department.getParentId());
            doctorVo1.setDepartmentParentName(department1.getDepartmentName());

            return doctorVo1;
        }).collect(Collectors.toList());

        //放数据，返回
        voPage.setRecords(DoctorVos);
        return voPage;
    }

    @Override
    public Result addDoctor(Doctor doctor) {

        if(doctor.getDepartmentId() == null ){
            return Result.fail().message("必须选择子级科室");
        }
        if(doctor.getDoctorName() == null ){
            return Result.fail().message("必须填写医生名称");
        }


        int insert = baseMapper.insert(doctor);
        return insert == 1 ? Result.ok() : Result.fail().message("保存失败！");
    }

    @Override
    public Result updataDoctor(Doctor doctor) {
        int updata = baseMapper.updateById(doctor);
        return updata>0 ? Result.ok() : Result.fail().message("更新失败！");
    }

    @Override
    public Result getDoctorById(Integer id) {
        //查询出该医生的信息
        Doctor doctor = baseMapper.selectById(id);
        DoctorVo doctorVo = new DoctorVo();
        BeanUtils.copyProperties(doctor,doctorVo);

        //查询出该医生的科室信息
        Department department = departmentService.getById(doctor.getDepartmentId());
        doctorVo.setDepartmentId(department.getId());
        doctorVo.setDepartmentParentName(department.getDepartmentName());
        doctorVo.setDepartmentParentId(department.getParentId());
        return Result.ok(doctorVo);


    }

    @Override
    @Transactional   //添加事务
    public Result deleteDoctorById(int id) {
        //条件构造器
        LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
        //查找跟这个id相同的医生id排班信息
        queryWrapper.eq(Schedule::getDoctorId, id);
        //删除医生排班信息
        boolean remove = scheduleService.remove(queryWrapper);
        //删除医生信息
        int flag = baseMapper.deleteById(id);
        if(remove&&flag>=1){
            return Result.ok();
        }else{
            return Result.fail().message("删除失败！");
        }
    }

    @Override
    @Transactional   //添加事务
    public Result batchDeleteDoctorByIds(List<Integer> ids) {
        boolean f =true;
        for (Integer id : ids) {
            //条件构造器
            LambdaQueryWrapper<Schedule>queryWrapper = new LambdaQueryWrapper<>();
            //查找跟这个id相同的医生id排班信息
            queryWrapper.eq(Schedule::getDoctorId, id);
            //删除医生排班信息
            boolean remove = scheduleService.remove(queryWrapper);
            //删除医生信息
            int flag = baseMapper.deleteById(id);
            if(remove&&flag!=1) {
                f = false;
                break;
            }
        }
        if(f){
            return Result.ok();
        }else {
            return Result.fail().message("删除失败！");
        }

    }

    public List<Doctor> getDoctorByName(List<String> doctorName){
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Doctor::getDoctorName,doctorName);
        List<Doctor> doctors = doctorService.list(queryWrapper);
        return doctors;
    }

    public List<Doctor> getDoctorByDepartmentIds(List<Long> departmentIds){
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        if(departmentIds.size()>0){
            queryWrapper.and(wq->{
                for(int i=0;i<departmentIds.size();i++){
                    if(i==0){
                        wq.eq(Doctor::getDepartmentId,departmentIds.get(i));
                    }
                    else{
                        wq.or().eq(Doctor::getDepartmentId,departmentIds.get(i));
                    }
                }
            });
        }else{
            queryWrapper.eq(Doctor::getDepartmentId,0);
        }
        List<Doctor> doctors = doctorService.list(queryWrapper);
        return doctors;
    }

    @Override
    public List<Doctor> getDoctorsByDepartmentId(String depcode) {
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getDepartmentId, depcode);

        List<Doctor> doctors = baseMapper.selectList(queryWrapper);
        return doctors;
    }

    @Override
    public List<Doctor> getList(String adminId) {
        Admin admin = getAdmin(adminId);
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getHospitalId, admin.getHospitalId());

        List<Doctor> doctors = baseMapper.selectList(queryWrapper);
        return doctors;
    }

    private Admin getAdmin(String adminId) {
        Object adminObj = adminFeignClient.getAdminById(Integer.valueOf(adminId)).getData();
        return JSONObject.parseObject(JSON.toJSONString(adminObj), Admin.class);
    }
}





